﻿using AppExample;
using LinqToTwitter;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace SafeTraveller.Controllers
{
    public class OAuthController : Controller
    {
        private const String ConsumerKey = "ay6t0YBkUs5Qm0mGQSYCqg";
        private const String ConsumerSecret = "WKztDXhDZXXOflRX4kMFMiFZMxpA3GRamymvfoqOI";
        /*private const String AccessToken = "410717395-lPfBBNvrniVquxF39R20arnohvZimv2kkEwK9K4o";
        private const String AccessTokenSecret = "S6d6D6Ms4obW3szvQsGSwJcnVtbffV9XIyfwk6RI2RlmM";*/
        readonly IOAuthCredentials credentials = new SessionStateCredentials();

        MvcAuthorizer auth;
        TwitterContext twitterCtx;

        String dateFrom = "01.01.2014";
        String dateTo = "02.01.2014";
        String Type = "epidemic|crime|political";

        public ActionResult Index(string datefrom, string dateto, string type)
        {
            dateFrom = datefrom;
            dateTo = dateto;
            Type = type;

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey = ConsumerKey;
                credentials.ConsumerSecret = ConsumerSecret;
            }

            auth = new MvcAuthorizer
            {
                Credentials = credentials
            };

            // internally, this doesn't execute if BeginAuthorization hasn't been called yet
            //  but it will execute after the user authorizes your application
            auth.CompleteAuthorization(Request.Url);

            // this will only execute if we don't have all 4 keys, which is what IsAuthorized checks
            if (!auth.IsAuthorized)
            {
                Uri specialUri = new Uri(Request.Url.ToString());

                // url param is optional, it lets you specify the page Twitter redirects to.
                // You can use it to complete the OAuth process on another action/controller - in which
                // case you would move auth.CompleteAuthorization to that action/controller.
                return auth.BeginAuthorization(specialUri);
            }


            extract(auth);

            

         

            

            return RedirectToAction("Index", "Home");
            
          /* //var auth = new MvcSignInAuthorizer
            var auth = new MvcAuthorizer
            {
                Credentials = new SessionStateCredentials
                {
                    ConsumerKey = OAuthController.ConsumerKey,
                    ConsumerSecret = OAuthController.ConsumerSecret,/*
                    AccessToken = OAuthController.AccessToken,
                    OAuthToken = "410717395-lPfBBNvrniVquxF39R20arnohvZimv2kkEwK9K4o"
                }
            };

            string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
            return auth.BeginAuthorization(new Uri(twitterCallbackUrl));*/
        }

        private void extract(ITwitterAuthorizer auth)
        {
            
            
            


/* в обработчик --------------------------------- */
            String path = AppDomain.CurrentDomain.BaseDirectory;
            System.IO.StreamWriter file = new System.IO.StreamWriter(path + "data.csv");
            file.WriteLine("date,territory,count,risk");

            StringBuilder sb = new StringBuilder();
           
            DateTime from, to;
            if (!DateTime.TryParse(dateFrom, out from))
                from = new DateTime(2012, 1, 1);
            if (!DateTime.TryParse(dateTo, out to))
                to = new DateTime(2015, 1, 1);
            //поиск по индии
            if (Type.Contains("epidemic")){
                queryCountry("India", "22.659065,79.077637,1000km", "epidemic", "epidemic OR disease", auth, file, from, to);
                queryCountry("China", "33.160025,107.598145,1500km", "epidemic", "epidemic OR disease", auth, file, from, to);
                queryCountry("Algeria", "27.804517,3.096191,870km", "epidemic", "epidemic OR disease", auth, file, from, to);
            }
            if (Type.Contains("crime")){
                queryCountry("India", "22.659065,79.077637,1000km", "crime", "murder OR homicide OR battery", auth, file, from, to);
                queryCountry("China", "33.160025,107.598145,1500km", "crime", "murder OR homicide OR battery", auth, file, from, to);
                queryCountry("Algeria", "27.804517,3.096191,870km", "crime", "murder OR homicide OR battery", auth, file, from, to);
            }
            if (Type.Contains("political")){
                queryCountry("India", "22.659065,79.077637,1000km", "political", "riot", auth, file, from, to);
                queryCountry("China", "33.160025,107.598145,1500km", "political", "riot", auth, file, from, to);
                queryCountry("Algeria", "27.804517,3.096191,870km", "political", "riot", auth, file, from, to);
            }

            file.Flush();
            file.Close();

            UploadData();
           
            
    /*------------------------------------------------*/
        }

        private void queryCountry(string country, string geocode, string type, string typekeys, ITwitterAuthorizer auth, StreamWriter file, DateTime from, DateTime to)
        {
            var twitterCtx = new TwitterContext(auth);
            try
            {
                var rawResult =
                   (from raw in twitterCtx.Search
                    where
                       raw.Query == typekeys /* "epidemic OR disease" */ &&
                       raw.Type == SearchType.Search &&
                       raw.Count == 1000 &&
                       raw.GeoCode == geocode /* "22.659065,79.077637,1000km" */


                    select raw)
                   .FirstOrDefault();

                foreach (var status in rawResult.Statuses)
                {
                    if (status.CreatedAt >= from)
                        file.WriteLine("{0:d2}.{1:d2}.{2},{3},{4},{5}",
                            status.CreatedAt.Month, status.CreatedAt.Day, status.CreatedAt.Year, country, 1, type);
                }
            }
            catch (Exception ex)
            {
            }
        }

       /* public ActionResult BeginCompleted()
        {
            var auth = new MvcAuthorizer
            {
                Credentials = new SessionStateCredentials()
            };

            bool ret = auth.CompleteAuthorization(Request.Url);

            // This is how you access credentials after authorization.
            // The oauthToken and oauthTokenSecret do not expire.
            // You can use the userID to associate the credentials with the user.
            // You can save credentials any way you want - database, 
            //   isolated storage, etc. - it's up to you.
            // You can retrieve and load all 4 credentials on subsequent 
            //   queries to avoid the need to re-authorize.
            // When you've loaded all 4 credentials, LINQ to Twitter will let 
            //   you make queries without re-authorizing.
            //
            //var credentials = auth.CredentialStore;
            //string oauthToken = credentials.OAuthToken;
            //string oauthTokenSecret = credentials.OAuthTokenSecret;
            //string screenName = credentials.ScreenName;
            //ulong userID = credentials.UserID;
            //

            
            var twitterCtx = new TwitterContext(auth);
            var rawResult =
                (from raw in twitterCtx.RawQuery
                 where raw.QueryString == "http://search.twitter.com/search.json?q=%23epidemic"
                 select raw)
                .FirstOrDefault();

            return RedirectToAction("Index", "Home");
        }*/


        /*public ActionResult AsyncComplete()
        {
            var auth = new MvcAuthorizer
            {
                Credentials = new SessionStateCredentials()
            };

            bool ret = auth.CompleteAuthorization(Request.Url);

            // This is how you access credentials after authorization.
            // The oauthToken and oauthTokenSecret do not expire.
            // You can use the userID to associate the credentials with the user.
            // You can save credentials any way you want - database, 
            //   isolated storage, etc. - it's up to you.
            // You can retrieve and load all 4 credentials on subsequent 
            //   queries to avoid the need to re-authorize.
            // When you've loaded all 4 credentials, LINQ to Twitter will let 
            //   you make queries without re-authorizing.
            //
            //var credentials = auth.CredentialStore;
            //string oauthToken = credentials.OAuthToken;
            //string oauthTokenSecret = credentials.OAuthTokenSecret;
            //string screenName = credentials.ScreenName;
            //ulong userID = credentials.UserID;
            //
           
        }*/

        public static string CalculateSHA1(string text, Encoding enc)
        {
            byte[] buffer = enc.GetBytes(text);
            SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
            return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "").ToLower();
        }

        private void UploadData()
        {
            String path = AppDomain.CurrentDomain.BaseDirectory;
            FileStream fs = new FileStream(path + "data.csv", FileMode.Open, FileAccess.Read);
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
            fs.Close();

            // Generate post objects
            Dictionary<string, object> postParameters = new Dictionary<string, object>();
            postParameters.Add("filename", "data.csv");
            postParameters.Add("fileformat", "csv");
            postParameters.Add("file", new FormUpload.FileParameter(data, "data.csv", "application/vnd.ms-excel"));

            // Create request and receive response
            string postURL = ConfigurationSettings.AppSettings["url"] + "api?s=ImportService&withheader=1&name=data&delimiter=,";
            //"country","series","Unit","Date","Value"

            List<Field> fields = new List<Field>();
            fields.Add(new Field() { Name = "date", TypeName = "timestamp" });
            fields.Add(new Field() { Name = "territory", TypeName = "string" });
            fields.Add(new Field() { Name = "count", TypeName = "double" });
            fields.Add(new Field() { Name = "risk", TypeName = "string" });

            postURL += "&fields=" + JsonConvert.SerializeObject(fields);
            string userAgent = "Someone";
            String requestToken = Request["token"];
            if (requestToken == null)
                requestToken = ConfigurationSettings.AppSettings["token"];


            HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL,
                userAgent,
                postParameters,
                CalculateSHA1(ConfigurationSettings.AppSettings["secret"] + requestToken, Encoding.UTF8),
                int.Parse(ConfigurationSettings.AppSettings["appid"]));

            // Process response
            StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
            string fullResponse = responseReader.ReadToEnd();
            webResponse.Close();
            //info.Text = fullResponse;

            Schema s = JsonConvert.DeserializeObject<Schema>(fullResponse);

            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", "CI.openSource(" + s.Key + ");", true);
        }
    }
}
